package org.mcjug.locationmailer.util;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.mcjug.locationmailer.R;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;

public class LocationUtil {
	public static String getAddress(Location location, Context context) {
		String addressStr = null;
		if (location != null) {
			Geocoder gc = new Geocoder(context, Locale.getDefault());
			try {
				List<Address> addresses = gc.getFromLocation(
						location.getLatitude(), location.getLongitude(), 1);
				StringBuilder sb = new StringBuilder();
				if (addresses.size() > 0) {
					Address address = addresses.get(0);
					for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
						sb.append(address.getAddressLine(i)).append("\n");
					}
				}
			 
				int idx = sb.lastIndexOf("\n");
				if (idx != -1) {
					sb.replace(idx, idx+1, "");
				}
				addressStr = sb.toString();
			} catch (IOException e) {
			}			
		}
		
		if (addressStr == null) {
			addressStr = context.getString(R.string.msgNoAddress);
		}

		return addressStr;
	}	
}
